package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constant.WemediaConstants;
import com.heima.common.constant.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.utils.thread.UserThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private WmUserMapper userMapper;
    @Autowired
    private WmUserMapper wmUserMapper;


    /**
     * 人工审核文章
     *
     * @param wmNewsId
     * @return
     */
    @Override
    public ResponseResult<WmNewsVO> oneVoArticle(Integer wmNewsId) {
        if (wmNewsId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(wmNewsId);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        WmUser wmUser = userMapper.selectById(wmNews.getUserId());
        wmNewsVO.setName(wmUser.getName());
        return ResponseResult.okResult(wmNewsVO);
    }

    /**
     * 管理端查询自媒体文章
     *
     * @param newsAuthDto
     * @return
     */
    @Override
    public ResponseResult list_vo(NewsAuthDto newsAuthDto) {
        log.info("【参数】:{}", newsAuthDto);
        if (newsAuthDto == null || newsAuthDto.getPage() == null || newsAuthDto.getSize() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        IPage<WmNews> page = new Page<>(newsAuthDto.getPage(), newsAuthDto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
        if (newsAuthDto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, newsAuthDto.getStatus());
        }
        page = page(page, queryWrapper);

        List<WmNewsVO> wmNewsVOList = page.getRecords().stream()
                .map(wmNews -> {
                    WmNewsVO wmNewsVO = new WmNewsVO();
                    BeanUtils.copyProperties(wmNews, wmNewsVO);
                    WmUser wmUser = userMapper.selectById(wmNews.getUserId());
                    wmNewsVO.setName(wmUser.getName());
                    return wmNewsVO;
                })
                .collect(Collectors.toList());

        ResponseResult responseResult = new PageResponseResult(newsAuthDto.getPage(), newsAuthDto.getSize(), (int) page.getTotal());
        responseResult.setData(wmNewsVOList);
        return responseResult;
    }

    /**
     * 文章内容回显
     *
     * @param wmNewsId
     * @return
     */
    @Override
    public ResponseResult reCoverArticle(Integer wmNewsId) {
        if (wmNewsId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(wmNewsId);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        log.info("【检查参数】:{}",dto);
        //1.检查参数
        if(dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());

        //3.判断文章是否为发布状态
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章及文章内容状态
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
//            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));
            wmNews.setEnable(dto.getEnable());
            updateById(wmNews);
            log.info("【文章id】:{}",wmNews.getArticleId() );
            //发送消息通知article修改文章配置
            if(wmNews.getArticleId() != null){
                log.info("【kafka远程调用文章接口】");
                Map<String,Object> map = new HashMap<>();
                map.put("articleId",wmNews.getArticleId());
                map.put("enable",wmNews.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 提交文章
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDto dto){
        //1.校验参数
        log.info("【校验参数】WmNewsDto:{}",dto);
        if(dto.getChannelId()==null || dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或修改文章
        //copy WmNewsDto -> WmNews 【属性名词和类型相同才能拷贝】
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);

        //封面图片 list -> string
        if(dto.getImages()!=null && !dto.getImages().isEmpty()){
            String imageUrl = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imageUrl);
        }

        //如果图片封面为自动type = -1 --> type = null
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        log.info("【保存文章信息】:{}",wmNews);
        //保存文章信息
        saveOrUpdateNews(wmNews);

        //判断是否为草稿
        if(dto.getStatus().equals((short)0)){
            log.info("【草稿结束】");
            //草稿 结束
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿
        //保存文章内容图片与素材的关系
        //获取文章内容中的图片
        log.info("【非草稿继续执行关系表数据插入】");
        List<String> materials = compileUrl(dto.getContent());
        log.info("获取文章中的图片url:{}",materials);
        log.info("【保存文章图片到关系表中】");
        saveRelativeInfoForContent(materials,wmNews.getId());

        //保存文章封面图片与素材关系，如果布局为自动，则需要匹配封面图片
        log.info("【保存文章封面到关系表中】");
        saveRelativeInfoForCover(dto,wmNews,materials);

        //审核文章
        //log.info("【审核文章】");
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //判断设置发布时间是否为空
        if(wmNews.getPublishTime() == null){
            wmNews.setPublishTime(new Date());
        }
        log.info("【添加任务到延迟队列中】");
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());

        //返回结果
        log.info("【返回结果】");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面与图片素材关系
     * @param dto
     * @param wmNews
     * @param materials
     */
    @Transactional
    public void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();
        log.info("【获取封面中的图片url】:{}",images);
        //如果封面类型为自动
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            if(materials.size()>=3){
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }
            else if(materials.size() >= 1 && materials.size() < 3){
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }
            else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
        }
        //修改文章
        if(images!=null && !images.isEmpty()){
            wmNews.setImages(StringUtils.join(images, ","));
        }
        updateById(wmNews);
        //修改关系表
        if(images!=null && !images.isEmpty()){
            log.info("【封面不为空时新增封面素材关系】:{}",images);
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }

    }

    /**
     * 存放图片和文章内容关系
     * @param materials
     * @param newsId
     */
    @Transactional
    public void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials,newsId,WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存图片与素材的关系到数据库中
     * @param materials
     * @param newsId
     * @param type
     */
    @Transactional
    public void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if(materials!=null && !materials.isEmpty()){
            //通过图片url获取素材id
            List<WmMaterial> materialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                    .in(WmMaterial::getUrl, materials));
            //非空判断
            if(materialList==null || materialList.size()==0){
                //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            //判断素材是否有效
            if(materialList.size() != materials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            //获取素材id列表
            List<Integer> idList = materialList.stream().map(WmMaterial::getId).collect(Collectors.toList());
            log.info("【通文章内容中的素材id列表】:{}",idList);
            //批量插入文章图片与素材关系内容
            wmNewsMaterialMapper.saveRelations(idList,newsId,type);

        }
    }


    /**
     * 提取文章中图片的url
     * @param content
     */
    private List<String> compileUrl(String content) {
        List<String> urls = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content,Map.class);
        maps.forEach(map -> {
           if(map.get("type").equals("image")){
               String url = (String)map.get("value");
               urls.add(url);
           }
        });
        return urls;
    }

    /**
     * 新增或修改文章内容
     * @param wmNews
     */
    @Transactional
    public void saveOrUpdateNews(WmNews wmNews) {
        //提交时间(修改时间)
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(UserThreadLocalUtil.getUser());
        //id = null 则是新增
        if(wmNews.getId()==null){
            //创建时间
            wmNews.setCreatedTime(new Date());
            save(wmNews);
        }else{
            //修改 删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }

    }

    /**
     * 人工审核成功
     *
     * @param newsAuthDto
     * @return
     */
    @Override
    public ResponseResult authPass(NewsAuthDto newsAuthDto) {
        if (newsAuthDto == null || newsAuthDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(newsAuthDto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        wmNews.setStatus(newsAuthDto.getStatus().shortValue());
        //审核成功,添加到任务任务列表中
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, wmNews.getId()).set(WmNews::getStatus, wmNews.getStatus()));
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());

        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 人工审核失败
     *
     * @param newsAuthDto
     * @return
     */
    @Override
    public ResponseResult authFail(NewsAuthDto newsAuthDto) {
        if (newsAuthDto == null || newsAuthDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(newsAuthDto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmNews.setStatus(newsAuthDto.getStatus().shortValue());
        wmNews.setReason(newsAuthDto.getMsg());
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 条件查询自媒体文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listNews(WmNewsPageReqDto dto) {
        log.info("【检查参数】WmNewsPageReqDto:{}",dto);
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2.分页查询
        log.info("【分页查询】");
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //状态筛选
        if(dto.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //发布时间筛选
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            //查询时间在...之间 between
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //查询频道筛选
        if(dto.getChannelId() != null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //关键字筛选
        if(dto.getKeyword() != null){
            //关键字模糊查询
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //获取当前发布人文章
        queryWrapper.eq(WmNews::getUserId, UserThreadLocalUtil.getUser());
        //发布时间倒叙排序
        queryWrapper.orderByDesc(WmNews::getPublishTime);

        page = page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        log.info("【分页查询结果】:{}条数据",page.getTotal());
        return responseResult;

    }
}
